﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Threading;
using System.Web;

namespace MulticastTV
{

    /// <summary>
    /// Recording scheduler form
    /// TODO: Culture dependent Date format, Get rid of hardcoded translations. 
    /// </summary>
    public partial class RecForm : Form
    {
        string daily = "";
        string weekly = "";

        Thread unth = null;
        VlmHttpRequests httpreq = null;
        
        /// <summary>
        /// Application startup path
        /// </summary>
        string path;
       
        /// <summary>
        /// Constructor
        /// </summary>
        public RecForm(string pth)
        {
            InitializeComponent();
            path = pth;
        }

        private void Form2_Load(object sender, EventArgs e)
        {

            DateTime curdate = DateTime.Now;
            curdate = new DateTime(curdate.Year, curdate.Month, curdate.Day, curdate.Hour, curdate.Minute, 0);
            dateTimePicker1.CustomFormat = "dd-MM-yyyy    HH:mm";
            dateTimePicker3.CustomFormat = "dd-MM-yyyy    HH:mm";
            DataView sort = new DataView(ChannelTable.menu.Tables["Menu"]);
            sort.Sort = ChannelTable.menu.Tables["Menu"].Columns[2].ColumnName;
            sort.RowFilter = ChannelTable.menu.Tables["Menu"].Columns[8].ColumnName.ToString() + " <> True"; //skip false
            bindingSource2.DataSource = sort;
            comboBox1.DataSource = bindingSource2;
            comboBox2.DataSource = bindingSource2;
           
            dateTimePicker1.Value = curdate.AddMinutes(1);
            dateTimePicker3.Value = curdate.AddHours(1).AddMinutes(1);
            dateTimePicker4.Value = curdate.AddMinutes(1);
            dateTimePicker2.Value = curdate.AddHours(1).AddMinutes(1);

            comboBox1.DisplayMember = ChannelTable.menu.Tables["Menu"].Columns[2].ColumnName;
            comboBox1.ValueMember = ChannelTable.menu.Tables["Menu"].Columns[0].ColumnName;
            comboBox2.DisplayMember =  ChannelTable.menu.Tables["Menu"].Columns[2].ColumnName;
            comboBox2.ValueMember = ChannelTable.menu.Tables["Menu"].Columns[0].ColumnName;

            dataGridView1.Columns["Column1"].DataPropertyName = "Start";
            dataGridView1.Columns["Column2"].DataPropertyName = "Stop";
            dataGridView1.Columns["Column3"].DataPropertyName = "Channel";
            dataGridView1.Columns["Column4"].DataPropertyName = "Duration (min)";
            dataGridView1.Columns["Column5"].DataPropertyName = "Repeat" ;
            dataGridView1.Columns["Column5"].Visible = false;  
            dataGridView1.Columns["Column6"].DataPropertyName = "Ip"; 
            dataGridView1.Columns["Column6"].Visible = false;
            dataGridView1.Columns["Column7"].DataPropertyName = "Name";
            //                   ["Column8"] status img
            //                   ["Column9"] delete button
            dataGridView1.Columns["Column10"].DataPropertyName = "Status";
            dataGridView1.Columns["Column10"].Visible = false;
            dataGridView1.Columns["Column11"].DataPropertyName = "object";
            dataGridView1.Columns["Column11"].Visible = false;
            //                   ["Column12"] Repeat img
            dataGridView1.Columns["Column13"].DataPropertyName = "action";
            dataGridView1.Columns["Column13"].Visible = false;
            //                   ["Column14"] action img
            
            bindingSource1.DataSource = RecTableContainer.dt.Tables[0];
            dataGridView1.DataSource = bindingSource1;
         }

        private void button1_Click(object sender, EventArgs e)
        {
            if (checkBox1.Checked)  daily = "daily"; 
            if (checkBox2.Checked) weekly = "weekly";
            if (!checkBox1.Checked) daily = "";
            if (!checkBox2.Checked) weekly = "";
            int act = 0;
            if (checkBox3.Checked)
                act = 1;
            else if (checkBox4.Checked)
                act = 2;
            else if (checkBox5.Checked)
                act = 3;
            
            TimeSpan duration = dateTimePicker3.Value.Subtract(dateTimePicker1.Value);
            if (duration.TotalMinutes > 0)
            {
                DataRow addrow = RecTableContainer.dt.Tables[0].NewRow();
                addrow[0]=dateTimePicker1.Value;
                addrow[1]=dateTimePicker3.Value;
                addrow[2]=((DataRowView)comboBox1.SelectedItem)["Name"];
                addrow[3]=duration.TotalMinutes;
                addrow[4]=daily + " " + weekly;
                addrow[5]=comboBox1.SelectedValue;
                addrow[6]="pending";
                addrow[7]=textBox1.Text;
                addrow[9]=act;
                RecTableContainer.dt.Tables[0].Rows.Add(addrow);
             }  
             button2.Enabled = true;
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            int DeleteIndex = dataGridView1.Columns["Column9"].Index;
            int ObjectIndex = dataGridView1.Columns["Column11"].Index;
            int StringStatusIndex = dataGridView1.Columns["Column10"].Index;
            int ShutdownAction = dataGridView1.Columns["Column14"].Index;

            if (e.ColumnIndex == DeleteIndex)
            {
                try
                {
                    if (!dataGridView1.Rows[e.RowIndex].Cells[StringStatusIndex].Value.Equals("recording"))
                    {
                        dataGridView1.Rows.RemoveAt(e.RowIndex);
                        button2.Enabled = true;
                    }
                    else
                    {
                        string confirm = "";
                        // TODO: Use Mlmessages.resx
                        if (Properties.Settings.Default.language=="Slovenian")
                            confirm = "Ali ste prepričani? Snemanje bo prekinjeno."; 
                        else
                            confirm = "Really delete?";

                        if (MessageBox.Show(confirm, "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {
                            DataRowView rowview = ((DataRowView)dataGridView1.Rows[e.RowIndex].DataBoundItem);
                            DataRow row = rowview.Row;
                            StandBy.sched_stop(row[5].ToString(), row[2].ToString(), row, (Rec)row[8],0);
                            dataGridView1.Rows.RemoveAt(e.RowIndex);
                            StandBy.callLoadTimerJobs();
                        }
                    }
                }
                catch {dataGridView1.Rows.RemoveAt(e.RowIndex); }
            }
            if (e.ColumnIndex == ShutdownAction && e.RowIndex != -1)
            {
                DataRowView rowview = ((DataRowView)dataGridView1.Rows[e.RowIndex].DataBoundItem);
                DataRow row = rowview.Row;
                int CurAct = 0;

                int.TryParse(row[9].ToString(), out CurAct);
                CurAct++;
                if (CurAct > 3)
                    CurAct = 0;
                row[9] = CurAct;
                button2.Enabled = true;

            }
        }

        private void Form2_FormClosing(object sender, FormClosingEventArgs e)
        {
            StandBy.callLoadTimerJobs();
            StandBy.prepeareWakeupTimer();
            RecTableContainer.dt.Tables["Recordings"].WriteXml(Globals.UserAppPath + @"\..\schedule.xml");
        }

        private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {

            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                //status images
                if (row.Cells["Column10"].Value != null && row.Cells["Column10"].Value.Equals("pending"))
                {
                    row.Cells["Column8"].Value = Properties.Resources.hourglass;
                }
                else if (row.Cells["Column10"].Value != null && row.Cells["Column10"].Value.Equals("done"))
                {
                    row.Cells["Column8"].Value = Properties.Resources.accept;
                }
                else if (row.Cells["Column10"].Value != null && row.Cells["Column10"].Value.Equals("recording"))
                {
                    row.Cells["Column8"].Value = Properties.Resources.RecordHot;
                }
                else
                    row.Cells["Column8"].Value = Properties.Resources.Blank16;

                //repeat images
                if (row.Cells["Column5"].Value != null && row.Cells["Column5"].Value.ToString().Contains("daily"))
                {
                    row.Cells["Column12"].Value = Properties.Resources.date;
                    if (Properties.Settings.Default.language=="Slovenian")
                        row.Cells["Column12"].ToolTipText = "dnevno";
                    else
                        row.Cells["Column12"].ToolTipText = "daily";
                }
                else if (row.Cells["Column5"].Value != null && row.Cells["Column5"].Value.ToString().Contains("weekly"))
                {
                    row.Cells["Column12"].Value = Properties.Resources.date_add;
                   if (Properties.Settings.Default.language=="Slovenian")
                        row.Cells["Column12"].ToolTipText = "tedensko";
                   else
                        row.Cells["Column12"].ToolTipText = "weekly";
                }
                else
                    row.Cells["Column12"].Value = Properties.Resources.Blank16;

                // action images
                if (row.Cells["Column13"].Value != null && row.Cells["Column13"].Value.ToString().Equals("1"))
                {
                    row.Cells["Column14"].Value = Properties.Resources.standby;
                }
                else if (row.Cells["Column13"].Value != null && row.Cells["Column13"].Value.ToString().Equals("2"))
                {
                    row.Cells["Column14"].Value = Properties.Resources.hibernate;
                }
                else if (row.Cells["Column13"].Value != null && row.Cells["Column13"].Value.ToString().Equals("3"))
                {
                    row.Cells["Column14"].Value = Properties.Resources.shutdown;
                }
                else
                {
                    row.Cells["Column14"].Value = Properties.Resources.Blank16;
                }
            }
       }

        private void button2_Click(object sender, EventArgs e)
        {
             StandBy.callLoadTimerJobs();
             StandBy.prepeareWakeupTimer();
             button2.Enabled = false;
             RecTableContainer.dt.Tables["Recordings"].WriteXml(Globals.UserAppPath + @"\..\schedule.xml");
        }

        private void checkBox1_CheckStateChanged(object sender, EventArgs e)
        {
            if (checkBox1.CheckState == CheckState.Checked)
                checkBox2.CheckState = CheckState.Unchecked;
        }

        private void checkBox2_CheckStateChanged(object sender, EventArgs e)
        {
            if (checkBox2.CheckState == CheckState.Checked)
                checkBox1.CheckState = CheckState.Unchecked;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {

        }

        private void checkBox3_CheckStateChanged(object sender, EventArgs e)
        {
            if (checkBox3.CheckState == CheckState.Checked)
            {
                checkBox4.CheckState = CheckState.Unchecked;
                checkBox5.CheckState = CheckState.Unchecked;
            }
        }

        private void checkBox4_CheckStateChanged(object sender, EventArgs e)
        {
            if (checkBox4.CheckState == CheckState.Checked)
            {
                checkBox3.CheckState = CheckState.Unchecked;
                checkBox5.CheckState = CheckState.Unchecked;
            }
        }

        private void checkBox5_CheckStateChanged(object sender, EventArgs e)
        {
            if (checkBox5.CheckState == CheckState.Checked)
            { 
                checkBox3.CheckState = CheckState.Unchecked;
                checkBox4.CheckState = CheckState.Unchecked;
            }
        }

        //Remote functions UNFINISHED***********************************

        private void checkServer()
        {
            UnicastConntest ctest = new UnicastConntest();
            ctest.check(Properties.Settings.Default.VlcIp, Properties.Settings.Default.VlcPort, label14, true);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            loadFromServer();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            sendToServer();
        }

        private void loadFromServer()
        {
            string sched = "";
            if (httpreq == null)
                httpreq = new VlmHttpRequests();
            unth = new Thread(new ThreadStart(httpreq.Send));

        }

        private void sendToServer()
        {
            
            //new my_media broadcast enabled
            //setup my_media input my_video.mpeg input my_other_movie.mpeg
            //setup my_media output #standard{mux=ts,access=udp,dst=239.255.1.1,sap,name="My Media"}

            //new my_sched schedule enabled
            //setup my_sched date 2012/12/12-12:12:12
            //setup my_sched append control my_media play


            string vlm = Properties.Settings.Default.VlmName;
            string host = Properties.Settings.Default.DestIp;
            string dest = "udp://" + Properties.Settings.Default.DestIp + ":" + Properties.Settings.Default.DestPort;
            List<string> commands = new List<string>();
            
            foreach (DataGridViewRow dgw in dataGridView2.Rows)
            {
                commands.Add("new "+dgw.Cells[6].Value+" broadcast enabled");
                commands.Add("setup "+dgw.Cells[6].Value+" input udp://@"+dgw.Cells[5].Value);
                commands.Add("setup " + dgw.Cells[6].Value + " output udp://@" + dgw.Cells[5].Value);
            }
          
            // clear previous vlm

            // set new vlm
            //string t1 = "GET /requests/vlm_cmd.xml?command=del+" + vlm + " HTTP/1.1\r\nHost: " + host + "\r\nConnection: Keep-Alive\r\nKeep-Alive: 3000\r\n\r\n";
            //string t2 = "GET /requests/vlm_cmd.xml?command=new+" + vlm + "+broadcast+enabled HTTP/1.1\r\nHost: " + host + "\r\nConnection: Keep-Alive\r\nKeep-Alive: 3000\r\n\r\n";
            //string t3 = "GET /requests/vlm_cmd.xml?command=setup+" + vlm + "+input+" + HttpUtility.UrlEncode(inputuni, Encoding.ASCII) + " HTTP/1.1\r\nHost: " + host + "\r\nConnection: Keep-Alive\r\nKeep-Alive: 3000\r\n\r\n";
            //string t4 = "GET /requests/vlm_cmd.xml?command=setup+" + vlm + "+output+" + HttpUtility.UrlEncode(dest, Encoding.ASCII) + " HTTP/1.1\r\nHost: " + host + "\r\nConnection: Keep-Alive\r\nKeep-Alive: 3000\r\n\r\n ";
            //string t5 = "GET /requests/vlm_cmd.xml?command=control+" + vlm + "+play HTTP/1.1\r\nHost: " + host + "\r\nConnection: Keep-Alive\r\nKeep-Alive: 3000\r\n\r\n";
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl1.SelectedIndex == 1)
                checkServer();
        }

    }
}
